package com.atguigu.chap0106;

import java.util.concurrent.*;

public class TicketSale {

    private static final int TOTAL_TICKETS = 50;
    private static final int SELLERS_COUNT = 3;
    private static int ticketsLeft = TOTAL_TICKETS;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(SELLERS_COUNT);
        Callable<Void> ticketSellerTask = new TicketSeller();
        
        // 提交任务给线程池
        Future<?>[] sellers = new Future[SELLERS_COUNT];
        for (int i = 0; i < SELLERS_COUNT; i++) {
            sellers[i] = executor.submit(ticketSellerTask);
        }

        // 等待所有售票员完成工作
        for (Future<?> seller : sellers) {
            seller.get(); // 这会阻塞直到对应的callable执行完毕
        }

        // 关闭线程池
        executor.shutdown();
        System.out.println("全部票已卖完");
    }

    private static class TicketSeller implements Callable<Void> {
        @Override
        public Void call() throws Exception {
            while (true) {
                synchronized (TicketSale.class) {
                    if (ticketsLeft > 0) {
                        // 模拟售票操作
                        Thread.sleep(10); // 假设每次售票需要一点时间
                        System.out.println(Thread.currentThread().getName() + "剩余票数： " + --ticketsLeft);
                    } else {
                        break; // 如果没有更多的票可以卖了，则退出循环
                    }
                }
            }
            return null;
        }
    }
}